<?php


namespace app\service;


class ImUserService
{


    /**
     * 用户充值
     * @param array $params
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author lilongfei
     * @date 2022-04-08 14:57
     */
    public static function charge($params = [])
    {

        try{
            $mobile = \think\facade\Db::name('user')->where('id',$params['user_id'])->value('mobile',0);
            //$mobile = '13512345678';
            $user = \think\facade\Db::connect('im')
                ->name('user')
                ->where('username',$mobile)
                ->find();
            if(!$user){
                return false;
            }
            $userId = $user['id'];
            \think\facade\Db::connect('im')
                ->name('user')->setInc('money',$params['amount']);

            $serviceMoney = self::getConfig('recharge_fee');
            if($user['is_enterprise']){
                $params['amount'] = $params['amount'] - $serviceMoney;
            }else{
                $serviceMoney = 0;
            }
            \think\facade\Db::connect('im')
                ->name('capital_log')->insert([
                    'user_id'=>$userId,
                    'order_id'=>'',
                    'capital_type'=>2,
                    'record_type'=>1,
                    'explain'=>'在线充值',
                    'user_money'=>$user['money'] +$params['amount'] + $serviceMoney ,
                    'money'=>$params['amount']+$serviceMoney
                ]);
            if($user['is_enterprise']){//充值手续费
                $addServiceChargeLog = [
                    'user_id'       => $userId,
                    'money'         => $serviceMoney,
                    'capital_type'  => 1, //充值
                    'remark'        => '充值服务费',
                    'user_money'    => $user['money']+$params['amount'],
                ];
                self::addServiceChargeLog($addServiceChargeLog);
            }
    }catch(\Exception $e){

        }

    }


    /**
     * 添加服务费
     * @param $param
     * @return int|string
     * @author lilongfei
     * @date 2022-04-08 15:08
     */
    public static function addServiceChargeLog($param)
    {
        return \think\facade\Db::connect('im')
            ->name('service_charge_log')->insert($param);
    }


    /**
     *获取配置信息
     */
    public static function getConfig($type)
    {
        $config = \think\facade\Db::connect('im')
            ->name('im_bsys_config')->where('field_key','pay_config')->find();

        $field_val = json_decode($config['field_val'],true);
        $serviceMoney = $field_val[$type] ?? 0;
        if(!$serviceMoney){
            $serviceMoney = 0;
        }
        return $serviceMoney;
    }



}